"use strict"
var fs = require('fs');

try{                            //全局配置检测
    if(fs.statSync('./config/global_setting.json')){
        LB.log.ok("全局配置加载成功！");
    }
}
catch(err){                     //配置文件错误
    LB.log.busy("全局配置不存在，正在自动创建...")
    fs.writeFileSync('./config/global_setting.json',JSON.stringify({"qq_id":"","qq_password":"","qq_group":{"management":"","chat":""},"administrators":[],"use_protocol":5,"login_way":1,"server_name":"Dedicated Server","ws_listen":"0.0.0.0:996","ws_mode":0,"ws_password":"abaabaabaaba","reconnect_interval":5,"features":{"player_join&amp;left_nofication":true,"player_die_nofication":true,"chat_forward":true,"blackbe":{"join_group_nofication":true,"join_group_request_auto_process":true}}},null,"\t"));
    LB.log.info("全局配置创建成功！请先修改配置文件，再启动LiteBot\n")
    process.exit(0)
};

var global_setting = JSON.parse(fs.readFileSync('./config/global_setting.json','utf8'));
LB.CONFIG.global = global_setting;
LB.bot = {};

const loginway = global_setting.login_way;      //登录方式，0：扫码登录，1：密码登录）
const account = global_setting.qq_id;           //qq号码
const qq_passwd = global_setting.qq_password;   //qq密码
const conf = {//机器人内部配置
    platform: global_setting.use_protocol,
    kickoff: false,
    ignore_self: true,
    resend: true,
    brief: true,
    log_level: "info"
}

const qq_client = require("oicq").createClient(account,conf)

switch(loginway){   //选择登录方式
    case 0:
        qq_client.on("system.login.qrcode", function (e) {
            //this.LB.log.busy("扫码后按Enter完成登录") 
            process.stdin.once("data", () => {
                this.login()
            })
        })
        .on("system.login.error", function (e) {
            if (e.code < 0)
                this.login()
        })
        .login()
    break;

    case 1:
        qq_client.on("system.login.slider", function (event) {
            this.LB.log.info("需要验证滑块登录！") 
            process.stdin.once("data", (input) => {
                this.sliderLogin(input);
            });
        }).on("system.login.device", function (event) {
            this.LB.log.busy("验证完成后按Enter开始登录") 
            process.stdin.once("data", () => {
                this.login();
            });
        }).login(qq_passwd);
    break;
}

qq_client.on("system.online",()=> LB.log.ok("LiteBot登录成功，开始处理消息"));
/*
.on("system.offline.network",()=> LB.log.warn("登录失败，可能是网络连接中断、服务器繁忙或需要验证，将会尝试重新登录"))
.on("system.offline.kickoff",()=> LB.log.error("账号已在其他同类客户端上线，将会退出登录"))
.on("system.offline.frozen",()=> LB.log.error("账号异常，将不会登录"));
*/

qq_client.on("request.group.add",function(e){       //加群监听
    if(LB.CONFIG.global.features.blackbe.join_group_request_auto_process){
        let c = LB.EXTENSION.blackbe("qq",e.user_id,1)
        qq_client.setGroupAddRequest(e.flag,c.operation)
        if(LB.CONFIG.global.features.blackbe.join_group_nofication != true){  //检查是否已启用云黑功能
            return
        }
        LB.bot.toMgmtGroup(LB.HELPER.MSG.getBlackbeOption("join_group_nofication",e.nickname,e.user_id,c.result,c.details,c.from_server,e.comment,c.action))
    }
})
.on("notice.group.decrease",function(e){   //退群监听
    let qq = e.user_id
    let xboxid = LB.HELPER.APD.getXboxID(qq)
    if(xboxid != undefined){
        LB.HELPER.APD.unbindXboxID(qq)
        LB.bot.toMgmtGroup(LB.HELPER.MSG.getGroupEvent("member_left_with_bind",qq,xboxid))
    }
    else{
        LB.bot.toMgmtGroup(LB.HELPER.MSG.getGroupEvent("member_left",qq))
    }
});

qq_client.on("message.group", function(e){      //群消息监听
    LB.MAIN.GROUP.forEach(element=>{
        try{
            element(e);
        }
        catch(err){
            LB.log.error('异常信息：'+err);
            return err
        }
    });
});

LB.bot.setGroupCard = function(qq,xid){     //设置群名片
    if(qq_client.online_status != 11) {
        LB.log.info(qq_client.online_status)
        LB.log.warn('[OICQ]','已阻止调用API：QQ未登录');
        return;
    }
    for(let n in global_setting.qq_group.chat){
        qq_client.setGroupCard(global_setting.qq_group.chat[n],qq,xid)
    }
}

LB.bot.GroupMessage = function(groupID,msg){     //发送群消息
    if(qq_client.online_status != 11) {
        LB.log.info(qq_client.online_status)
        LB.log.warn('[OICQ]','已阻止调用API：QQ未登录');
        return;
    }
    qq_client.sendGroupMsg(groupID,msg)
}

LB.bot.toMgmtGroup = (msg)=>{       //发送到指令群
    LB.bot.GroupMessage(global_setting.qq_group.management,msg)
}

LB.bot.toChatGroup = (msg)=>{       //发送到聊天群
    LB.bot.GroupMessage(global_setting.qq_group.chat,msg)
}